from sqlalchemy import Column, Integer, String, Text, DateTime, ForeignKey, Boolean, JSON
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from app.core.database import Base

class KnowledgeDocument(Base):
    """知识文档基本信息表"""
    __tablename__ = "knowledge_documents"
    
    id = Column(Integer, primary_key=True, index=True)
    user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
    title = Column(String(255), nullable=False)
    filename = Column(String(255), nullable=False)
    file_path = Column(String(512), nullable=False)  # 存储文件在服务器上的路径
    file_size = Column(Integer)  # 文件大小，单位为字节
    file_type = Column(String(50))  # 文件类型，如pdf, docx, txt等
    source_url = Column(String(512), nullable=True)  # 来源URL，可选
    status = Column(String(20), default="uploaded")  # 状态：uploaded, processing, indexed, failed
    vector_store_id = Column(String(100), nullable=True)  # 向量数据库中的ID
    vector_store_type = Column(String(50), nullable=True)  # 向量数据库类型
    extra_metadata = Column(JSON, nullable=True)  # 存储其他元数据
    created_at = Column(DateTime, server_default=func.now())
    updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now())
    
    # 关系
    user = relationship("User")
    versions = relationship("KnowledgeVersion", back_populates="document", cascade="all, delete-orphan")
    activities = relationship("DocumentActivity", back_populates="document", cascade="all, delete-orphan")
    permissions = relationship("DocumentPermission", back_populates="document", cascade="all, delete-orphan")
    sections = relationship("DocumentSection", back_populates="document", cascade="all, delete-orphan")


class KnowledgeVersion(Base):
    """文档版本历史表"""
    __tablename__ = "knowledge_versions"
    
    id = Column(Integer, primary_key=True, index=True)
    document_id = Column(Integer, ForeignKey("knowledge_documents.id", ondelete="CASCADE"), nullable=False)
    version_number = Column(Integer, nullable=False, default=1)
    content_hash = Column(String(255), nullable=True)  # 内容哈希，用于检测变更
    file_path = Column(String(512), nullable=True)  # 历史版本文件路径
    created_at = Column(DateTime, server_default=func.now())
    created_by = Column(Integer, ForeignKey("users.id"), nullable=True)
    
    # 关系
    document = relationship("KnowledgeDocument", back_populates="versions")
    created_by_user = relationship("User")


class DocumentActivity(Base):
    """文档操作记录表"""
    __tablename__ = "document_activities"
    
    id = Column(Integer, primary_key=True, index=True)
    document_id = Column(Integer, ForeignKey("knowledge_documents.id", ondelete="CASCADE"), nullable=False)
    user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
    action_type = Column(String(50), nullable=False)  # 操作类型：upload, update, delete, view, download
    action_detail = Column(Text, nullable=True)  # 操作详情
    created_at = Column(DateTime, server_default=func.now())
    
    # 关系
    document = relationship("KnowledgeDocument", back_populates="activities")
    user = relationship("User")


class DocumentPermission(Base):
    """文档权限表"""
    __tablename__ = "document_permissions"
    
    id = Column(Integer, primary_key=True, index=True)
    document_id = Column(Integer, ForeignKey("knowledge_documents.id", ondelete="CASCADE"), nullable=False)
    user_id = Column(Integer, ForeignKey("users.id"), nullable=True)  # 可为空，表示公共文档或特定角色
    role_id = Column(Integer, ForeignKey("roles.id"), nullable=True)  # 角色ID，可扩展角色权限系统
    can_view = Column(Boolean, default=False)
    can_edit = Column(Boolean, default=False)
    can_delete = Column(Boolean, default=False)
    can_share = Column(Boolean, default=False)
    created_at = Column(DateTime, server_default=func.now())
    updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now())
    
    # 关系
    document = relationship("KnowledgeDocument", back_populates="permissions")
    user = relationship("User")
    role = relationship("Role", back_populates="permissions")


class DocumentSection(Base):
    """文档片段表，用于存储文档的分段信息"""
    __tablename__ = "document_sections"
    
    id = Column(Integer, primary_key=True, index=True)
    document_id = Column(Integer, ForeignKey("knowledge_documents.id", ondelete="CASCADE"), nullable=False)
    section_index = Column(Integer, nullable=False)  # 片段索引
    content = Column(Text, nullable=False)  # 片段内容
    extra_metadata = Column(JSON, nullable=True)  # 片段元数据，如页码、章节等
    vector_store_chunk_id = Column(String(100), nullable=True)  # 向量数据库中的片段ID
    created_at = Column(DateTime, server_default=func.now())
    
    # 关系
    document = relationship("KnowledgeDocument", back_populates="sections")


class Role(Base):
    """角色表，用于权限控制"""
    __tablename__ = "roles"
    
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(50), unique=True, nullable=False)  # 角色名称：admin, editor, viewer
    description = Column(String(255), nullable=True)
    created_at = Column(DateTime, server_default=func.now())
    updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now())
    
    # 关系
    permissions = relationship("DocumentPermission", back_populates="role")
    users = relationship("User", secondary="user_roles", back_populates="roles")


class UserRole(Base):
    """用户角色关联表"""
    __tablename__ = "user_roles"
    
    id = Column(Integer, primary_key=True, index=True)
    user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
    role_id = Column(Integer, ForeignKey("roles.id", ondelete="CASCADE"), nullable=False)
    created_at = Column(DateTime, server_default=func.now())